package com.union.core.sys.model;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

/**
 * @获取管理用户在线的单例
 * @projectname：cocotour
 * @packagename：com.duomi.core.sys.model
 * @filename：SysManagerSessionList.java
 * @date：2011-3-30 下午05:37:17
 * @author: wangxiuwu
 */
public class SysManagerSessionList {
	
	private List<HttpSession> mgrSessionList;
	private static SysManagerSessionList instance = null;

	public SysManagerSessionList() {
		mgrSessionList = new ArrayList<HttpSession>();   
	}
	
    /**
     * 返回一个SysManagerList类的单一实例
     * @return instance
     */
    public synchronized  static SysManagerSessionList getInstance(){
            if(instance == null){
                    instance = new SysManagerSessionList();
            }
            return instance;
    }
    
    /**
     * 增加在线用户session
     * @param mgrSession HttpSession
     */
    public void addSession(HttpSession mgrSession){   
        if (mgrSession != null){   
        	mgrSessionList.add(mgrSession);   
        }   
    }   
  
    /**
     * 删除在线用户session
     * @param storeSession HttpSession
     */
    public void removeSession(HttpSession mgrSession){   
        if (mgrSession != null){
        	mgrSessionList.remove(mgrSession);  			//将session从队列中删除
        	mgrSession.removeAttribute("sysManager");		//将session失效，阻止该session登陆系统
        }
    } 
  
    /**
     * 获取在线用户session列表
     * @return List
     */
    public List<HttpSession> getSessionList(){
        return mgrSessionList;   
    }
    
	/**
	 * 获取在线用户人数
	 * @return int
	 */
	public int getSessionCount() {
		return mgrSessionList.size();
	}
	
	/**
	 * 判断用户是否已在线
	 * @param loginAccount
	 * @return boolean
	 */
	public boolean existMgrSession(String loginAccount) {
		boolean existMgrSession = false;
		for (int i = 0; i < mgrSessionList.size(); i++) {
			SysManager manager = (SysManager)mgrSessionList.get(i).getAttribute("sysManager");
			
			//判断是否为空，若为空，则把该空值从队列中去掉
			if(null == manager){
				mgrSessionList.remove(i); //把空值从队列中去掉
			}else{
				if(loginAccount.equals(manager.getMANAGER_NAME())){
					existMgrSession = true;
					break;
				}
			}
		}
		return existMgrSession;
	}
    
	/**
     * 根据帐户取出单个在线用户mgrSession
     * @param mgrSession HttpSession
     * @return
     */
    public HttpSession getMgrSession(String loginAccount){
    	HttpSession mgrSession = null;
    	for (int i = 0; i < mgrSessionList.size(); i++) {
    		SysManager manager = (SysManager)mgrSessionList.get(i).getAttribute("sysManager");
			if(loginAccount.equals(manager.getMANAGER_NAME())){
				mgrSession = mgrSessionList.get(i);
				break;
			}
		}
		return mgrSession;
    }
	

}
